const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer <token>

  if (!token) {
    return res.status(401).json({
      code: 3,
      message: '未提供Token',
      success: false
    });
  }

  jwt.verify(token, JWT_SECRET, (err, decoded) => {
    if (err) {
      if (err.name === 'TokenExpiredError') {
        return res.status(401).json({
          code: 4,
          message: 'Token已过期',
          success: false
        });
      }
      return res.status(403).json({
        code: 5,
        message: '无效Token',
        success: false
      });
    }

    // 将解码的用户信息挂载到请求对象
    req.user = decoded;
    next();
  });
}

module.exports = authenticateToken;
